# -*- coding: utf-8 -*-
from django import forms
from django.core.exceptions import ValidationError
from qcloud_cos import CosServiceError

from utils.tencent.cos import check_file
from web import models
from web.forms.bootstrap import BootStrapForm


class FolderModelForm(BootStrapForm, forms.ModelForm):
    class Meta:
        model = models.FileRepository
        fields = ['name']
    
    def __init__(self, request, parent_obj, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request
        self.parent_obj = parent_obj
    
    def clean_name(self):
        
        name = self.cleaned_data['name']
        queryset = models.FileRepository.objects.filter(file_type=2, name=name, project=self.request.tracer.project)
        # 当前文件夹下是否已存在
        # 如果有父级对象
        if self.parent_obj:
            exists = queryset.filter(parent=self.parent_obj).exists()
        else:
            exists = queryset.filter(parent__isnull=True).exists()
        if exists:
            raise ValidationError('文件已经存在')
        return name


class FileModelForm(forms.ModelForm):
    etag = forms.CharField(label='etag')
    
    class Meta:
        model = models.FileRepository
        exclude = ['project', 'file_type', 'update_user']

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
    
        self.request = request
        
    def clean_file_path(self):
        
        return 'https://{}'.format(self.cleaned_data['file_path'])

    def clean(self):
        key = self.cleaned_data['key']
        etag = self.cleaned_data['etag']
        size = self.cleaned_data['file_size']
        
        if not key or not etag:
            return self.cleaned_data
        
        # 校验cos文件合法
        try:
            res = check_file(self.request.tracer.project.bucket, self.request.tracer.project.region, key)
            
        except CosServiceError as e:
            self.add_error(key, '文件不存在')
            return self.cleaned_data
        
        cos_etag = res.get('ETag')
        if etag != cos_etag:
            self.add_error('etag', 'ETag错误')
        
        cos_length = res.get('Content-Length')
        if int(cos_length) != size:
            self.add_error('size', '文件大小错误')
        
        return self.cleaned_data
